//
//  SettingsViewController.m
//  CheckersGame
//
//  Created by Guest User on 11-12-02.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "SettingsViewController.h"
#import "checkers_players/CheckersAIPlayer.h"
#import "checkers_players/CheckersHumanPlayer.h"
#import "BoardViewController.h"
#import "AppDelegate.h"//fix this

@implementation SettingsViewController

@synthesize currentView, selectDifficulty1, selectDifficulty2, playerName1, playerName2, aiSwitch1, aiSwitch2;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //[self.selectDifficulty setEnabled:NO forSegmentAtIndex:1];
    //[self.selectDifficulty setEnabled:NO forSegmentAtIndex:2];
    [self.selectDifficulty1 setEnabled:YES forSegmentAtIndex:3];
    [self.selectDifficulty2 setEnabled:YES forSegmentAtIndex:3];
    playerName1.delegate = self;
    playerName2.delegate = self;
    
    self.navigationItem.title = @"New Game";
    self.title = @"New Game";
    
    // Observe keyboard hide and show notifications to resize the text view appropriately.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [self->rightSwipe addTarget:self action:@selector(handleRightSwipe:)];
    [self.view addGestureRecognizer:rightSwipe];
    //self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Begin" style:UIBarButtonItemStyleBordered target:self action:@selector(didSelectPlay:)];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidDisappear:(BOOL)animated {
    [self.playerName1 resignFirstResponder];
    [self.playerName2 resignFirstResponder];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self hideKeyboard];
}

- (IBAction)hideKeyboard
{
    [self.playerName1 resignFirstResponder];
    [self.playerName2 resignFirstResponder];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return NO;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)didSelectDifficulty:(id)sender 
{
    [self hideKeyboard];
    
    if (sender==selectDifficulty1)
    {
        playerName1.text = [NSString stringWithFormat:
                                @"CPU level %d", self.selectDifficulty1.selectedSegmentIndex];
    }
    else
    {
        playerName2.text = [NSString stringWithFormat:
                                @"CPU level %d", self.selectDifficulty2.selectedSegmentIndex];
    }
}

- (IBAction)didSelectAI:(id)sender
{
    [self hideKeyboard];
    
    if (sender==aiSwitch1)
    {
        if (aiSwitch1.on)
        {
            playerName1.text = [NSString stringWithFormat:
                                @"CPU level %d", self.selectDifficulty1.selectedSegmentIndex];
            playerName1.enabled = NO;
            self.selectDifficulty1.enabled = YES;
        }
        else
        {
            playerName1.text = @"";
            playerName1.enabled = YES;
            self.selectDifficulty1.enabled = NO;
        }
    }
    else if (sender==aiSwitch2)
    {
        if (aiSwitch2.on)
        {
            playerName2.text = [NSString stringWithFormat:
                                @"CPU level %d", self.selectDifficulty2.selectedSegmentIndex];
            playerName2.enabled = NO;
            self.selectDifficulty2.enabled = YES;
        }
        else
        {
            playerName2.text = @"";
            playerName2.enabled = YES;
            self.selectDifficulty2.enabled = NO;
        }
    }
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    [self resizeViewForKeyBoard:YES withNotification:notification];  
}


- (void)keyboardWillHide:(NSNotification *)notification 
{
    [self resizeViewForKeyBoard:NO withNotification:notification];
}


- (void)handleRightSwipe:(UIGestureRecognizer *)gestureRecognizer {
    // Initialize the game board controller, reuse the one in memory if possible
    CheckersGameState* gameState = [[CheckersGameState alloc] init];

    NSString *name1 = ([self.playerName1.text isEqualToString:@""])? @"Player 1": self.playerName1.text;
    NSString *name2 = ([self.playerName2.text isEqualToString:@""])? @"Player 2": self.playerName2.text;
    BoardViewController* boardController = [[BoardViewController alloc] init];
    boardController.timeout = self->timeoutSlider.value;
    boardController.player1 = name1;
    boardController.player2 = name2;
    boardController.pvp = !(self.aiSwitch1.on || self.aiSwitch2.on);
    boardController.ai_player1 = self.aiSwitch1.on;
    boardController.ai_player2 = self.aiSwitch2.on;
    boardController.managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    [self.navigationController pushViewController:boardController animated:YES];
            
    if (!self.aiSwitch1.on){
        CheckersHumanPlayer *p1= [[CheckersHumanPlayer alloc] init];
        p1.playerName = name1;
        //p1.playerName = self.playerName1.text;
        gameState.player1 = p1;
    }
    else 
        gameState.player1 = [ [CheckersAIPlayer alloc] 
            initDifficulty: self.selectDifficulty1.selectedSegmentIndex];
    
    if (!self.aiSwitch2.on){
        CheckersHumanPlayer *p2= [[CheckersHumanPlayer alloc] init];
        p2.playerName = name2;
        //p2.playerName = self.playerName2.text;
        gameState.player2 = p2;
    }
    else 
        gameState.player2 = [ [CheckersAIPlayer alloc] 
            initDifficulty: self.selectDifficulty2.selectedSegmentIndex];
    
    // Send a new game message
    [boardController newGame: gameState];
}

- (void)resizeViewForKeyBoard:(BOOL)showKeyboard withNotification:(NSNotification *)notification
{
    self->rightSwipe.enabled = !rightSwipe.enabled;
    
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    CGRect rect = self.view.frame;
    if (showKeyboard)
    {
        rect.origin.y -= kbSize.height/2.5;
    }
    else
    {
        rect.origin.y += kbSize.height/2.5;
    }
    
    self.view.frame = rect; 
    [UIView commitAnimations];
}

- (IBAction)timeoutChanged:(UISlider *)sender
{
    self->timeoutLabel.text = [NSString stringWithFormat:@"%1.0f sec", sender.value]; 
}

- (IBAction)timeoutTouched:(id)sender
{
    self->rightSwipe.enabled = NO;
}

- (IBAction)timeoutUpdated:(id)sender
{
    self->rightSwipe.enabled = YES;
}

@end
